//
//  AppDelegate.swift
//  SinaWeibo
//
//  Created by 林柱强 on 16/1/28.
//  Copyright © 2016年 林柱强. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        let account = UserAccount.loadAccount()
        print(account)
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()
        
        //设置主题色
        setThemeColor()
        
        //注册通知
        registerNotification()
        
        //判断是否新版本
        print("----------------")
        
        window?.rootViewController = defaultRootController()
        
        return true
    }
    
    //MARK: 监听通知
    private func registerNotification() {
        //object  观测某个对象发出的通知 如果为nil  就是观测所有的对象发出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootVC:", name: APPSwitchRootViewController, object: nil)
    }
    
    @objc private func switchToRootVC(notification: NSNotification) {
        let view = notification.object == nil ? MainViewController() : WelComeViewController()
        window?.rootViewController = view
    }
    
    //MARK: 移除通知  编码规范而已 没有任何作用
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    //MARK: 判断用户是否登陆 并且是否是更新版本
    private func defaultRootController() -> UIViewController {
        if UserAccount.userLogin() {
            return isNewVersion() ? NewFeatureViewController() : WelComeViewController()
        }
        return MainViewController()
    }
    
    func setThemeColor(){
        UINavigationBar.appearance().tintColor = themeColor
        UITabBar.appearance().tintColor = themeColor
    }
    
    //MARK: 检测是否是新版本
    private func isNewVersion() -> Bool {
        //比较新旧版本
        //1.获取新版本
        let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionNum = Double(versionStr)
        
        //获取旧版本
        let key = "sandBoxKey"
        let userdefaults = NSUserDefaults.standardUserDefaults()
        let lastVersion = userdefaults.doubleForKey(key)
        
        //保存新版本
        userdefaults.setDouble(versionNum!, forKey: key)
        //同步沙盒
        userdefaults.synchronize()
        
        //比较版本
        return versionNum! > lastVersion
    }

}

